package com.web.aspect;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.common.annotation.OriginalReturn;
import com.common.apiresult.CommonResult;
import com.common.apiresult.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author liuxuhuang
 * @date 2023年04月07日 22:22
 * @desc aop 处理统一返回结果
 */
@ControllerAdvice(basePackages = "com.web")
@Component
@Slf4j
public class ResultAspect implements ResponseBodyAdvice {
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("aop开始处理返回结果");
        Method method = methodParameter.getMethod();
        if (method.isAnnotationPresent(OriginalReturn.class)) {
            log.info("忽略注释--");
            return body;
        }
        log.info("结果集：" + body.toString());
        if (Objects.isNull(body) || StrUtil.isEmptyIfStr(body) || StrUtil.isBlankIfStr(body) || StringUtils.isBlank(body.toString())) {
            log.info("返回结果空");
            return CommonResult.failed(ResultCode.RETURNNULL);
        }
        if (body instanceof String) {
            return objectMapper.writeValueAsString(CommonResult.success(body));
        }
        if (body instanceof CommonResult) {
            return body;
        }
        return CommonResult.success(body);
    }
}
